<?php
defined('_JEXEC') or die();

class WrdControllerDiscountoff extends JControllerLegacy 
{
    protected $option;
	protected $controller; 
    
	function __construct( $default = array()){
		$this->option = 'com_wrd';
		$this->controller = 'discountoff';
		parent::__construct( $default );
	}

	function display()
	{
		switch($this->getTask()){
		case 'add':{
			JRequest::setVar( 'hidemainmenu', 1 );
			JRequest::setVar( 'layout', 'form'  );
			JRequest::setVar( 'view'  , 'discountoff');
		} 
				break;
            default:
				JRequest::setVar( 'view'  , 'discountoff');
            	break;
		}

		parent::display();
	}
        
      //save profile info
    function save(){
	   $post=JRequest::get('post');
       $post['created_date'] = date("Y-m-d H:i:s");
       $post['o_code_tmp'] = serialize($post['o_code']);
       unset($post['o_code']);
       $post['o_code'] = $post['o_code_tmp'];
       unset($post['o_code_tmp']);
       $params = JComponentHelper::getParams('com_wrd');
       $model = $this->getModel('discount');
       
       if($post['rule'] != 5)
       		$post['lucky'] = '';
       else{
       		$luckynum_arr = explode(',', $post['lucky']);
       		foreach ($luckynum_arr as $num=>$val){
       			$luckynum_arr[$num] = trim($val);
       		}
       		
       		$post['lucky'] = serialize($luckynum_arr);
       }
       
       //get date current  
       $outlet = $this->getModel("outlets");
       $id_category = $model->store($post,'discountoff',$outlet->getList());
	   
       if($id_category != 0){
       		 //save to server
		   	$server_ip = '10.1.6.6';
		   	$port = '55759';
		   	date_default_timezone_set('Asia/Ho_Chi_Minh');
			$timezone  = +7;
			$db = JFactory::getDBO();
			
			$server_post = array();
			if(intval($post[id]) != 0){
				$server_post[id] = strval($post[id]);
				$logfile_sucess = '-update-sucess.txt';
				$logfile_failure = '-update-failure.txt';
			}
			else{
				$server_post[id] = strval($db->insertid());
				$logfile_sucess = '-add-sucess.txt';
				$logfile_failure = '-add-failure.txt';
			}
				
			$server_post[title] = strval($post[title]);
			$server_post[o_code]= strval(implode(',', unserialize($post[o_code])));
			$server_post[percent]= strval($post[percent]);
			$server_post[cash]= strval($post[cash]);
			
			if($post[published_up] != '')
				$server_post[published_up]= date('m/d/Y',strtotime($post[published_up]));
			else
				 $server_post[published_up] = '01/01/1970';
			
			if($post[published_down] != '')
				$server_post[published_down]= date('m/d/Y',strtotime($post[published_down]));
			else 
				$server_post[published_down] = '01/01/1970';

			$server_post[created_date]= strval(date('m/d/Y',strtotime($post[created_date])));
			$server_post[published]= strval($post[published]);
			$server_post[priority]= strval($post[priority]);
			$server_post[rule]= strval($post[rule]);
			$server_post[lucky]= strval(implode(',', unserialize($post[lucky])));
			$server_post[message]= strval($post[message]);
			
			$target_url = $server_ip.':'.$port.'/MemberService.svc/updateDiscountPolicy';
			// Encode $POST into JSON Type
			$json = str_replace('\/','/',json_encode($server_post));
			
			// Send JSON files
			$result = WrdHelper::JSONSEND($target_url,$json);
			$path = JPATH_SITE.'/logs-wrd/';
			
			if($result == '\"success\"'){
				file_put_contents($path."discountpolicyoff/success/".date("Y-m-d").$logfile_sucess, $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
			else if($result == '') {
				file_put_contents($path."discountpolicyoff/failure/".date("Y-m-d").$logfile_failure, $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}

            $this->setRedirect('index.php?option=com_wrd&controller=discountoff','Saved');
            
            return true;                
       }
       else{
            $this->setRedirect('index.php?option=com_wrd&controller=discountoff','Error Saved');
            return false;
       }
    }    
   
    function remove()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to delete' ) );
		}

		$model = $this->getModel('discountoff');
		if(!$model->delete($cid)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		foreach($cid as $id){
			//save to server
		   	$server_ip = '10.1.6.6';
		   	$port = '55759';
		   	date_default_timezone_set('Asia/Ho_Chi_Minh');
			$timezone  = +7;
			$server_post = array();
			$server_post[id] = strval($id);
		
			$target_url = $server_ip.':'.$port.'/MemberService.svc/deleteDiscountPolicy';
			// Encode $POST into JSON Type
			$json = str_replace('\/','/',json_encode($server_post));
			
			// Send JSON files
			$result = WrdHelper::JSONSEND($target_url,$json);
			$path = JPATH_BASE.DS;
			if($result == '\"success\"'){
				file_put_contents($path."discountpolicyoff/success/".date("Y-m-d").'-remove-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
			else if($result == '') {
				file_put_contents($path."discountpolicyoff/failure/".date("Y-m-d").'-remove-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
		}
		
		$this->setRedirect( 'index.php?option=com_wrd&controller=discountoff' );
	}
   
    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>' ) );
		}

		$model = $this->getModel('discountoff');
		if(!$model->publish($cid, 1)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		
		foreach($cid as $id){
			$post = $model->getItem($id);
			
			//save to server
		   	$server_ip = '10.1.6.6';
		   	$port = '55759';
		   	date_default_timezone_set('Asia/Ho_Chi_Minh');
			$timezone  = +7;

			$server_post = array();
			$server_post[id] = strval($id);
			$server_post[title] = strval($post->title);
			$server_post[o_code]= strval(implode(',', unserialize($post->o_code)));
			$server_post[percent]= strval($post->percent);
			$server_post[cash]= strval($post->cash);
			
			if($post[published_up] != '0000-00-00')
				$server_post[published_up]= date('m/d/Y',strtotime($post[published_up]));
			else
				 $server_post[published_up] = '';
			
			if($post[published_down] != '0000-00-00')
				$server_post[published_down]= date('m/d/Y',strtotime($post[published_down]));
			else 
				$server_post[published_down] = '';
				
			$server_post[created_date]= strval(date('m/d/Y',strtotime($post->created_date)));
			$server_post[published]= strval($post->published);
			$server_post[priority]= strval($post->priority);
			$server_post[rule]= strval($post->rule);
			$server_post[lucky]= strval(implode(',', unserialize($post->lucky)));
			$server_post[message]= strval($post->message);
			
			$target_url = $server_ip.':'.$port.'/MemberService.svc/updateDiscountPolicy';
			// Encode $POST into JSON Type
			$json = str_replace('\/','/',json_encode($server_post));
			
			// Send JSON files
			$result = WrdHelper::JSONSEND($target_url,$json);
			
			if($result == '\"success\"'){
				file_put_contents($path."discountpolicyoff/success/".date("Y-m-d").'-publish-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
			else if($result == '') {
				file_put_contents($path."discountpolicyoff/failure/".date("Y-m-d").'-publish-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
		}
		exit();
		$this->setRedirect( 'index.php?option=com_wrd&controller=discountoff' );
	}

	function unpublish(){
		
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( '<p style="color:red">Please select an item to publish</p>'  ) );
		}

		$model = $this->getModel('discountoff');
		
		if(!$model->publish($cid, 0)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
		}
		
		foreach($cid as $id){
			$post = $model->getItem($id);
			
			//save to server
		   	$server_ip = '10.1.6.6';
		   	$port = '55759';
		   	date_default_timezone_set('Asia/Ho_Chi_Minh');
			$timezone  = +7;
			
			$server_post = array();
			$server_post[id] = strval($id);
			$server_post[title] = strval($post->title);
			$server_post[o_code]= strval(implode(',', unserialize($post->o_code)));
			$server_post[percent]= strval($post->percent);
			$server_post[cash]= strval($post->cash);
			
			if($post[published_up] != '0000-00-00')
				$server_post[published_up]= date('m/d/Y',strtotime($post[published_up]));
			else
				 $server_post[published_up] = '';
			
			if($post[published_down] != '0000-00-00')
				$server_post[published_down]= date('m/d/Y',strtotime($post[published_down]));
			else 
				$server_post[published_down] = '';
				
			$server_post[created_date]= strval(date('m/d/Y',strtotime($post->created_date)));
			$server_post[published]= strval($post->published);
			$server_post[priority]= strval($post->priority);
			$server_post[rule]= strval($post->rule);
			$server_post[lucky]= strval(implode(',', unserialize($post->lucky)));
			$server_post[message]= strval($post->message);
			
			$target_url = $server_ip.':'.$port.'/MemberService.svc/updateDiscountPolicy';
			// Encode $POST into JSON Type
			$json = str_replace('\/','/',json_encode($server_post));
			
			// Send JSON files
			$result = WrdHelper::JSONSEND($target_url,$json);
			if($result == '\"success\"'){
				file_put_contents($path."discountpolicyoff/success/".date("Y-m-d").'-unpublish-sucess.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
			else if($result == '') {
				file_put_contents($path."discountpolicyoff/failure/".date("Y-m-d").'-unpublish-failure.txt', $json." ".gmdate("H:i:s", time() + 3600*($timezone+date("0")))."\n",  FILE_APPEND | LOCK_EX);
			}
		}
		exit();
		$this->setRedirect( 'index.php?option=com_wrd&controller=discountoff' );
	}
}
?>